package com.arrays.a3_erfen;

/**
 * 04-20
 * 二分查找
 */
public class MidSearch {
    /*
    有效的完全平方数
     */
    public boolean isPerfectSquare(int num) {
        int l = 0, r = num;
        while (l < r) {
            int mid = l + r + 1 >> 1;
            if (mid * mid > num) {
                r = mid - 1;
            } else {
                l = mid;
            }
        }
        return r * r == num;
    }

    public boolean isPerfectSquare2(int num) {
        int left = 0, right = num;
        while (left <= right) {
            int mid = (right - left) / 2 + left;
            long square = (long) mid * mid;
            if (square < num) {
                left = mid + 1;
            } else if (square > num) {
                right = mid - 1;
            } else {
                return true;
            }
        }
        return false;
    }

    /*
    排硬币
     */
    public int arrangeCoins(int n) {
        int l = 1, r = n;
        while (l < r) {
            int mid = l + (r - l + 1) / 2;
            if (mid * (mid + 1) / 2 <= n) {
                l = mid;
            } else {
                r = mid - 1;
            }
        }
        return l;

    }


    public static void main(String[] args) {
        MidSearch midSearch = new MidSearch();
        int tar = 16;
        boolean res = midSearch.isPerfectSquare(tar);
        System.out.println(res);
    }
}
